
<!-- src/views/ResourceManagement.vue -->
<template>
  <div>
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline @submit.prevent="handleSearch">
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" :icon="Search" circle @click="handleSearch"/>
          <el-button :icon="Refresh" circle @click="resetSearch"/>
        </el-form-item>
      </el-form>

      <div class="mb-10px">
        <el-button type="primary" @click="handleAdd" circle :icon="Plus"/>
      </div>

      <!-- 卡片列表 -->
      <div class="card-container">
        <el-card
            v-for="item in resources"
            :key="item.id"
            class="resource-card"
            shadow="hover"
        >
          <div class="card-header">
            <h3 class="project-name" :title="item.projectName">{{ item.projectName }}</h3>
            <div class="card-actions">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(item)"
                  :icon="Edit"
                  circle
              />
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(item)"
                  :icon="Delete"
                  circle
              />
            </div>
          </div>

          <div class="card-content">
            <div class="info-item">
              <el-tag type="info" size="small" class="info-tag">IP</el-tag>
              <span class="info-value" :title="item.ip">{{ item.ip }}</span>
            </div>
            <div class="info-item">
              <el-tag type="info" size="small" class="info-tag">端口</el-tag>
              <span class="info-value">{{ item.port }}</span>
            </div>
            <div class="info-item">
              <el-tag type="info" size="small" class="info-tag">账号</el-tag>
              <span class="info-value" :title="item.username">{{ item.username }}</span>
            </div>
            <div class="info-item">
              <el-tag type="info" size="small" class="info-tag">密码</el-tag>
              <span class="info-value" :title="item.password">{{ item.password }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination-right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName" :rules="[{ required: true, message: '请输入项目名称', trigger: 'blur' }]">
              <el-input v-model="form.projectName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="form.type" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ip">
              <el-input v-model="form.ip" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input v-model="form.port" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前端目录" prop="frontendDir">
              <el-input v-model="form.frontendDir" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="后端目录" prop="backendDir">
              <el-input v-model="form.backendDir" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起始日期" prop="startDate">
              <el-date-picker
                  v-model="form.startDate"
                  type="date"
                  value-format="YYYY-MM-DD"                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete,Search,Refresh } from '@element-plus/icons-vue'
import 'dayjs/locale/zh-cn'

const resources = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref()

const form = ref({
  id: null,
  projectName: '',
  type: '',
  ip: '',
  port: '',
  username: '',
  password: '',
  frontendDir: '',
  backendDir: '',
  startDate: '',
  remark: ''
})

const searchForm = ref({
  projectName: ''
})

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取所有项目（分页查询）
const getResources = async () => {
  try {
    const result = await window.electronAPI.getResources({
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      projectName: searchForm.value.projectName || ''
    })

    resources.value = result.data
    pagination.value.total = result.total
  } catch (error) {
    console.error('获取项目失败:', error)
    ElMessage.error('获取项目列表失败: ' + (error.message || '未知错误'))
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  getResources()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.projectName = ''
  pagination.value.currentPage = 1
  getResources()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  getResources()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  getResources()
}

// 新增项目
const handleAdd = () => {
  dialogTitle.value = '新增项目'
  isEdit.value = false
  form.value = {
    id: null,
    projectName: '',
    type: '',
    ip: '',
    port: '',
    username: '',
    password: '',
    frontendDir: '',
    backendDir: '',
    startDate: '',
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑项目
const handleEdit = (row) => {
  dialogTitle.value = '编辑项目'
  isEdit.value = true
  // 创建一个新的对象，避免引用原始对象
  form.value = {
    id: row.id,
    projectName: row.projectName,
    type: row.type,
    ip: row.ip,
    port: row.port,
    username: row.username,
    password: row.password,
    frontendDir: row.frontendDir,
    backendDir: row.backendDir,
    startDate: row.startDate,
    remark: row.remark
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 创建一个干净的对象传递给 IPC
        const resourceData = {
          projectName: form.value.projectName,
          type: form.value.type,
          ip: form.value.ip,
          port: form.value.port,
          username: form.value.username,
          password: form.value.password,
          frontendDir: form.value.frontendDir,
          backendDir: form.value.backendDir,
          startDate: form.value.startDate,
          remark: form.value.remark
        }

        let result
        if (isEdit.value) {
          // 更新项目
          resourceData.id = form.value.id
          result = await window.electronAPI.updateResource(resourceData)
          ElMessage.success('更新成功')
        } else {
          // 新增项目
          result = await window.electronAPI.addResource(resourceData)
          ElMessage.success('添加成功')
        }

        if (result.success) {
          dialogVisible.value = false
          await getResources()
        } else {
          throw new Error('操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error((isEdit.value ? '更新' : '添加') + '失败: ' + (error.message || '未知错误'))
      }
    }
  })
}

// 删除项目
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const result = await window.electronAPI.deleteResource(row.id)
      if (result.success) {
        ElMessage.success('删除成功')
        await getResources()
      } else {
        throw new Error('删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

onMounted(() => {
  getResources()
})
</script>

<style scoped>.mb-10px {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
}

/* 卡片容器 */
.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
  background-color: #ffffff;
}

/* 资源卡片 */
.resource-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}

.resource-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.project-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

/* 卡片内容 */
.card-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-tag {
  width: 40px;
  text-align: center;
  color: #2bd99f;
  font-weight: bold;
}

.info-value {
  flex: 1;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: bold;
}

.password-field {
  font-family: monospace;
  letter-spacing: 1px;
}

/* 分页组件右对齐 */
.pagination-right {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 操作按钮样式优化 */
.el-button + .el-button {
  margin-left: 10px;
}

/* 表格操作列样式 */
.el-table .el-button--small {
  padding: 6px;
  width: 32px;
  height: 32px;
}

:deep(.el-popper) {
  max-width: 500px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-container {
    grid-template-columns: 1fr;
  }

  .project-name {
    max-width: 150px;
  }
}

/* 按钮悬停效果 */
:deep(.el-button.circle:hover) {
  transform: scale(1.1);
}
</style>